package com.epfresh.supplier.activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.widget.MultipleStatusView;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.*;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Goods;
import com.epfresh.supplier.entity.StatusEntity;
import com.epfresh.supplier.widget.WrapContentLinearLayoutManager;
import com.google.gson.Gson;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

public class PriceSureActivity extends BaseActivity {

    RecyclerView lv_deal_detail;
    MultiTypeAdapter mGoodsAdapter;

    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    List<Object> items = new ArrayList<>();

    PriceSureViewBinder mGoodsBinder;
    TextView[] tvSelect = new TextView[3];
    ArrayList<Goods> list = new ArrayList<>();

    String storeId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        //mHttpLoad();
    }
    private MultipleStatusView msvGoods;

    void initView(){
        setContentView(R.layout.activity_price_sure);
        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);
        tvBack.setVisibility(View.VISIBLE);
        ivBack.setVisibility(View.VISIBLE);
        toolbarTitle.setText("变价确认");
        tvSelect[0] = (TextView)findViewById(R.id.tv_up);
        tvSelect[1] = (TextView)findViewById(R.id.tv_down);
        tvSelect[2] = (TextView)findViewById(R.id.tv_hor);
        tvSelect[0].setOnClickListener(this);
        tvSelect[1].setOnClickListener(this);
        tvSelect[2].setOnClickListener(this);

        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setText("提交");
        rightbtn.setTextColor(0xff6f6f6f);
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intoPriceSure();
            }
        });


/*        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.ptr_ff);
        ptrFrameLayout.setPtrHandler(ptrHandler);*/

        lv_deal_detail = (RecyclerView)findViewById(R.id.lv_deal_detail);
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_deal_detail.setLayoutManager(layoutManager);

        mGoodsAdapter = new MultiTypeAdapter();
        mGoodsBinder = new PriceSureViewBinder();


        mGoodsBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(data instanceof Goods){
                    Goods goods = (Goods) data;
                    BigDecimal unit = getUnit(goods);
                    if(goods.getPriceNow()==null)
                        goods.setPriceNow(goods.getPrice());
                    if(view.getId()==R.id.iv_add){

                        goods.setPriceNow(unit.add(new BigDecimal(goods.getPriceNow())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                        if(goods.getPriceNow().doubleValue()>99999.99){
                            toast("价格不能大于99999.99");
                            goods.setPriceNow(99999.99);
                        }
                        if(goods.getPriceNow().doubleValue() == goods.getPrice().doubleValue()){
                            goods.setPriceNow(null);
                            DataManager.getInstance().removePriceGoods(goods.getId());
                        }else{
                            DataManager.getInstance().putPriceGoods(goods.getId(),goods);
                        }
                    }else{
                        if(goods.getPriceNow().doubleValue()==0){
                            toast("价格不能小于0");
                            return;
                        }
                        goods.setPriceNow((new BigDecimal(goods.getPriceNow()).subtract(unit)).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                        if(goods.getPriceNow().doubleValue() == goods.getPrice().doubleValue()){
                            goods.setPriceNow(null);
                            DataManager.getInstance().removePriceGoods(goods.getId());
                        }else{
                            DataManager.getInstance().putPriceGoods(goods.getId(),goods);
                        }
                    }
                    mGoodsAdapter.notifyDataSetChanged();
                }
            }
        });

        mGoodsAdapter.register(Goods.class, mGoodsBinder);


        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        mGoodsAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        lv_deal_detail.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setItems(items);
        loadMoreDelegate.attach(lv_deal_detail, loadMoreSubject);
        list.clear();
        items.clear();
        if(DataManager.getInstance().getPriceGoods()!=null){
            for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()>DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                    list.add(DataManager.getInstance().getPriceGoods().get(i));
                }
            }
            for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()<DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                    list.add(DataManager.getInstance().getPriceGoods().get(i));
                }
            }
        }
        items.addAll(list);
        mGoodsAdapter.notifyDataSetChanged();
    }
    boolean[] selectFlag = {true,true,false};
    void clickSelect(int pos){
        selectFlag[pos] = !selectFlag[pos];
        if(!selectFlag[0]&&!selectFlag[1]&&!selectFlag[2]){
            toast("至少选择一个筛选条件");
            selectFlag[pos] = !selectFlag[pos];
            return;
        }
        Log.e("pos","看看哪儿出错了"+pos);
        if(selectFlag[pos]){
            tvSelect[pos].setTextColor(Color.RED);
            mGoodsBinder.showFlag[pos] = true;
            tvSelect[pos].setBackgroundResource(R.drawable.btn_price_select);
        }else{
            mGoodsBinder.showFlag[pos] = false;
            tvSelect[pos].setTextColor(0xff666666);
            tvSelect[pos].setBackgroundResource(R.drawable.btn_price_unselect);
        }
        list.clear();
            if(mGoodsBinder.showFlag[2]){
                if(responseElement==null&&pos==2) {
                    reqGoodsList(0, new ArrayList<String>());
                    Log.e("request","看看哪儿出错了"+pos);
                    return;
                }else{
                    if(mGoodsBinder.showFlag[0]&&DataManager.getInstance().getPriceGoods()!=null){
                        for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                            if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()>DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                                list.add(DataManager.getInstance().getPriceGoods().get(i));
                            }
                        }
                    }
                    if(mGoodsBinder.showFlag[1]&&DataManager.getInstance().getPriceGoods()!=null){
                        for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                            if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()<DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                                list.add(DataManager.getInstance().getPriceGoods().get(i));
                            }
                        }
                    }
                    Log.e("responseElement","看看哪儿出错了"+pos);
                    list.addAll(responseElement.getContent());
                    items.clear();
                    items.addAll(list);
                    mGoodsAdapter.notifyDataSetChanged();
                    if(items==null||items.size()==0)
                        msvGoods.showEmpty();
                    else
                        msvGoods.showContent();
                    return;
                }
            }
        Log.e("未选中持平分支","看看哪儿出错了"+pos);

        if(mGoodsBinder.showFlag[0]&&DataManager.getInstance().getPriceGoods()!=null){
            for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()>DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                    list.add(DataManager.getInstance().getPriceGoods().get(i));
                }
            }
        }
        if(mGoodsBinder.showFlag[1]&&DataManager.getInstance().getPriceGoods()!=null){
            for(int i=DataManager.getInstance().getPriceGoods().size()-1;i>=0;i--){
                if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()<DataManager.getInstance().getPriceGoods().get(i).getPrice()){
                    list.add(DataManager.getInstance().getPriceGoods().get(i));
                }
            }
        }
        items.clear();
        items.addAll(list);
        mGoodsAdapter.notifyDataSetChanged();
        if(items==null||items.size()==0)
            msvGoods.showEmpty();
        else
            msvGoods.showContent();
    }


    private void intoPriceSure() {
        submit();
    }


    class PriceModel{
        String id;
        String price;
        public PriceModel(String id,String price){
            this.id = id;
            this.price = price;
        }
    }
    private void submit() {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_submitPrice);
        RequestEntityMapSupply.putParameter("storeId",BaseApplication.getInstance().getStoreId());
        if(DataManager.getInstance().getPriceGoods()!=null) {
            ArrayList list = new ArrayList();
            for (int i = 0; i < DataManager.getInstance().getPriceGoods().size(); i++) {
                if(DataManager.getInstance().getPriceGoods().get(i).getPriceNow()==null||DataManager.getInstance().getPriceGoods().get(i).getPriceNow()>99999.99){
                    toast("价格范围0-99999.99");
                    return;
                }
                PriceModel priceModel = new PriceModel(DataManager.getInstance().getPriceGoods().get(i).getId(),""+DataManager.getInstance().getPriceGoods().get(i).getPriceNow());
                list.add(priceModel);
            }
            RequestEntityMapSupply.putParameter("prices",list);
        }else{
            RequestEntityMapSupply.putParameter("prices",new ArrayList<>());
        }
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_submitPrice, onSubmitRequestListener);
    }

    OnRequestListener<StatusEntity> onSubmitRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            if (response != null){
                DataManager.getInstance().clearPriceGoods();
                StatusEntity responseElement = response.getResponseElement();
                toast("已更新价格");
                setResult(0x001);
                finish();
            }
        }
    };



    private BigDecimal getUnit(Goods goods){
        BigDecimal unit;
        if(goods.getPrice()*10%1>0){
            unit = new BigDecimal(0.01);
        }else if(goods.getPrice()*10%10>0){
            unit = new BigDecimal(0.1);
        }else{
            unit = new BigDecimal(1);
        }
        return unit;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_up:
                clickSelect(0);
                break;
            case R.id.tv_down:
                clickSelect(1);
                break;
            case R.id.tv_hor:
                clickSelect(2);
                break;
        }
    }
    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return true;//!ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            if(mGoodsBinder.showFlag[2]) {
                loadMoreDelegate.setStatusLoading();
                reqGoodsList(pageNum + 1, new ArrayList<String>());
            }
        }
    };
    int pageNum = 0;
    private void reqGoodsList(int pageNumber, List<String> ids) {
        for(int i=0;i<DataManager.getInstance().getPriceGoods().size();i++){
            ids.add(DataManager.getInstance().getPriceGoods().get(i).getId());
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_list4changePrice);
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("ids", ids);
        RequestEntityMapSupply.putParameter("pageSize", 20);
        RequestEntityMapSupply.putParameter("pageNumber", pageNumber);

        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_list4changePrice, onGoodsRequestListener);
    }

    private OnRequestListener<ContentEntity<Goods>> onGoodsRequestListener = new OnRequestListener<ContentEntity<Goods>>() {
        @Override
        public ContentEntity<Goods> jsonToObj(String responseStr) {
            hideProgressDialog();

            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, Goods.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Goods>> response, Object tag) {
            if (response != null) {
                responseElement = response.getResponseElement();
                int number = responseElement.getNumber();
                boolean last = responseElement.getLast();
                if(number == 0) {
                    items.clear();
                    list.clear();


                    if (mGoodsBinder.showFlag[0] && DataManager.getInstance().getPriceGoods() != null) {
                        for (int i = 0; i < DataManager.getInstance().getPriceGoods().size(); i++) {
                            if (DataManager.getInstance().getPriceGoods().get(i).getPriceNow() > DataManager.getInstance().getPriceGoods().get(i).getPrice()) {
                                list.add(DataManager.getInstance().getPriceGoods().get(i));
                            }
                        }
                    }
                    if (mGoodsBinder.showFlag[1] && DataManager.getInstance().getPriceGoods() != null) {
                        for (int i = 0; i < DataManager.getInstance().getPriceGoods().size(); i++) {
                            if (DataManager.getInstance().getPriceGoods().get(i).getPriceNow() < DataManager.getInstance().getPriceGoods().get(i).getPrice()) {
                                list.add(DataManager.getInstance().getPriceGoods().get(i));
                            }
                        }
                    }
                    //list.addAll(DataManager.getInstance().getPriceGoods());
                    list.addAll(responseElement.getContent());
                    loadMoreDelegate.addAllItem(items, list);
                }else{
                    loadMoreDelegate.addAllItem(items, responseElement.getContent());
                }
                if (last) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }
                mGoodsAdapter.notifyDataSetChanged();
                if(items==null||items.size()==0)
                    msvGoods.showEmpty();
                else
                   msvGoods.showContent();
            }

        }
    };

    ContentEntity<Goods> responseElement;
}
